package Testclass.ajaxTest;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ajax4")
public class ajax4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");//响应用户请求时，告知用户服务器的编码
        //获取json格式的字符串
        String datajson = req.getParameter("datajson");
        System.out.println("字符串datajson = " + datajson);
        //json格式转换json对象
        JSONObject jsonObject = JSONObject.parseObject(datajson.toString());
        //获取对象中各个属性的值
        String name1 = jsonObject.getString("name1");
        String age1 = jsonObject.getString("age1");

        //数据输出
        System.out.println("name1 = " + name1);
        System.out.println("age1 = " + age1);

        PrintWriter writer = resp.getWriter();
        writer.write("success");
    }
}
